package context.dao;

import context.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class Thumbs_upRepository {
    private final String SELECT_BY_ID = "select count(*) from thumbs_up where thumbs_up_userid=? and dynamicid=?";
    private final String COUNT = "SELECT COUNT(dynamicid) FROM thumbs_up WHERE dynamicid=?";
    private final String INSERT_USER = "insert into thumbs_up(thumbs_up_userid,dynamicid) values(?,?)";
    private JdbcTemplate jdbcTemplate;

    private Connection connection;
    @Autowired          //自动装配
    public Thumbs_upRepository(JdbcTemplate jdbcTemplate) throws SQLException {
        this.jdbcTemplate = jdbcTemplate;
        connection = jdbcTemplate.getDataSource().getConnection();
    }


    //增
    public void insertID(final long thumbs_up_userid, final long dynamicid) {

        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(INSERT_USER);
            ps.setLong(1, thumbs_up_userid);
            ps.setLong(2, dynamicid);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    //查点赞人与被点赞动态
    public int findThumbsByID(long thumbs_up_userid, long dynamicid) {

        try {
            return jdbcTemplate.queryForObject(SELECT_BY_ID, new RowMapper<Integer>() {
                @Override
                public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
                    return rs.getInt(1);
                }
            }, thumbs_up_userid, dynamicid);
        } catch (EmptyResultDataAccessException e) {
            return 0;
        }
    }

    //查点赞人数
    public long findThumbsCountByID(long thumbs_upid) {

        try {
            return jdbcTemplate.queryForObject(COUNT, new RowMapper<Long>() {
                @Override
                public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
                    return rs.getLong(1);
                }
            }, thumbs_upid);
        } catch (EmptyResultDataAccessException e) {
            return 0;
        }
    }

    private String DELTHUMB = "delete from thumbs_up where dynamicid=? and thumbs_up_userid=?";

    public void delThumb(long userid, long dynamicID) {
        jdbcTemplate.update(DELTHUMB, new Object[]{dynamicID, userid});
    }
}
